package pl.register.android.activities.students;

import android.app.AlertDialog;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import com.github.rtyley.android.sherlock.roboguice.fragment.RoboSherlockFragment;
import pl.register.android.R;
import pl.register.android.course.factory.CreatorCourseMonitoring;
import pl.register.android.database.exception.NotFoundCourseException;
import pl.register.android.activities.students.builder.DeleteStudentConfirmationDialogBuilder;
import pl.register.android.activities.students.builder.StudentEditorDialogBuilder;
import pl.register.android.activities.students.builder.YearEditorDialogBuilder;
import pl.register.android.activities.students.logic.AsyncStudentsLoader;
import pl.register.android.activities.students.logic.StudentsPresenter;
import pl.register.android.activities.students.ui.StudentListAdapter;
import pl.register.android.activities.students.ui.StudentsView;
import pl.register.android.course.Course;
import pl.register.android.course.dialog.CreatorNextCourseDialogBuilder;
import pl.register.android.course.dialog.NotFoundPreviousCourseDialogBuilder;
import pl.register.android.database.DatabaseAdapter;
import pl.register.android.preferences.ResotorePreferences;
import pl.register.android.student.Student;
import pl.register.android.year.Year;
import pl.register.android.year.YearType;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Mateusz Strzelecki
 * @since 2013-04-09
 */

public class StudentsFragment extends RoboSherlockFragment
        implements StudentsView, AdapterView.OnItemClickListener, CompoundButton.OnCheckedChangeListener, View.OnClickListener, CreatorCourseMonitoring {

    private ImageButton imageBtnPrevious;

    private ImageButton imageBtnNext;

    private Button btnTitle;

    private TextView tvStartYear;

    private TextView tvEndYear;

    private RadioButton rbFirstYear;

    private RadioButton rbSecondYear;

    private RadioButton rbThirdYear;

    private RadioButton rbIntensiveYear;

    private RadioButton rbHoliday1Year;

    private RadioButton rbHoliday2Year;

    private ListView lvStudents;

    private Button btnAddStudent;

    private Map<YearType, RadioButton> rbYearsMap;


    private DatabaseAdapter databaseAdapter;

    private StudentsPresenter presenter;

    private StudentListAdapter listAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View contentLayout = inflater.inflate(R.layout.students_layout, container, false);
        registerViews(contentLayout, inflater);
        setupContent();

        databaseAdapter = new DatabaseAdapter(getActivity());
        databaseAdapter.open();
        presenter = new StudentsPresenter(databaseAdapter, this);
        return contentLayout;
    }

    @Override
    public void onResume() {
        super.onResume();
        Course course = ResotorePreferences.getCourse(getActivity());
        new AsyncStudentsLoader(getActivity(), this, presenter, course).execute();
    }

    private void registerViews(View content, LayoutInflater inflater) {
        imageBtnPrevious = (ImageButton) content.findViewById(R.id.previous_button);
        imageBtnNext = (ImageButton) content.findViewById(R.id.next_button);
        btnTitle = (Button) content.findViewById(R.id.title_table_button);
        tvStartYear = (TextView) content.findViewById(R.id.start_year_date_text_view);
        tvEndYear = (TextView) content.findViewById(R.id.end_year_date_text_view);
        rbFirstYear = (RadioButton) content.findViewById(R.id.first_year_radio_button);
        rbSecondYear = (RadioButton) content.findViewById(R.id.second_year_radio_button);
        rbThirdYear = (RadioButton) content.findViewById(R.id.third_year_radio_button);
        rbIntensiveYear = (RadioButton) content.findViewById(R.id.intensive_year_radio_button);
        rbHoliday1Year = (RadioButton) content.findViewById(R.id.holiday_I_year_radio_button);
        rbHoliday2Year = (RadioButton) content.findViewById(R.id.holiday_II_year_radio_button);
        lvStudents = (ListView) content.findViewById(R.id.students_list_view);
        View footerView = inflater.inflate(R.layout.list_footer_add_student, null, false);
        btnAddStudent = (Button) footerView.findViewById(R.id.add_student_button);
        lvStudents.addFooterView(footerView);
    }

    private void setupContent() {
        listAdapter = new StudentListAdapter(getActivity());
        lvStudents.setAdapter(listAdapter);
        lvStudents.setOnItemClickListener(this);
        registerForContextMenu(lvStudents);

        imageBtnPrevious.setOnClickListener(this);
        imageBtnNext.setOnClickListener(this);
        btnTitle.setOnClickListener(this);
        btnAddStudent.setOnClickListener(this);

        rbYearsMap = new HashMap<YearType, RadioButton>();
        registerRadioButton(rbFirstYear, YearType.FIRST_YEAR);
        registerRadioButton(rbSecondYear, YearType.SECOND_YEAR);
        registerRadioButton(rbThirdYear, YearType.THIRD_YEAR);
        registerRadioButton(rbIntensiveYear, YearType.INTENSIVE_YEAR);
        registerRadioButton(rbHoliday1Year, YearType.HOLIDAY_I_YEAR);
        registerRadioButton(rbHoliday2Year, YearType.HOLIDAY_II_YEAR);
    }

    private void registerRadioButton(RadioButton radioButton, YearType yearType) {
        rbYearsMap.put(yearType, radioButton);
        radioButton.setText(yearType.getShortName());
        radioButton.setTag(yearType);
        radioButton.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getActivity().getMenuInflater().inflate(R.menu.context_menu_student, menu);
        menu.setHeaderTitle(R.string.dialog_title_select_options);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int position = info.position;
        Student clickedStudent = listAdapter.getItem(position);
        switch (item.getItemId()) {
            case R.id.menu_student_show_profile:
                presenter.goToProfile(getActivity(), clickedStudent);
                return true;
            case R.id.menu_student_edit:
                showEditStudentDialog(clickedStudent);
                return true;
            case R.id.menu_student_delete:
                showDeleteStudentConfirmationDialog(clickedStudent);
                return true;
        }
        return super.onContextItemSelected(item);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        Student clickedStudent = listAdapter.getItem(position);
        showEditStudentDialog(clickedStudent);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_student_button:
                showEditStudentDialog(Student.nullObject());
                break;
            case R.id.title_table_button:
                showEditYearDialog();
                break;
            case R.id.next_button:
                try {
                    presenter.rebuildForNextCourse(getActivity());
                } catch (NotFoundCourseException e) {
                    showCreateCourseDialog();
                }
                break;
            case R.id.previous_button:
                try {
                    presenter.rebuildForPreviousCourse(getActivity());
                } catch (NotFoundCourseException e) {
                    showNotFoundCourseDialog();
                }
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isSelected) {
        if (!isSelected) {
            return;
        }
        switch (buttonView.getId()) {
            case R.id.first_year_radio_button:
            case R.id.second_year_radio_button:
            case R.id.third_year_radio_button:
            case R.id.intensive_year_radio_button:
            case R.id.holiday_I_year_radio_button:
            case R.id.holiday_II_year_radio_button:
                YearType yearType = (YearType) buttonView.getTag();
                presenter.changeYearType(getActivity(), yearType);
                break;
        }
    }

    @Override
    public void populateStudents(List<Student> students) {
        listAdapter.refreshItems(students);
    }

    @Override
    public void populateCourse(String startYear, String endYear) {
        tvStartYear.setText(startYear);
        tvEndYear.setText(endYear);
    }

    @Override
    public void populateYears(List<Year> studentYears) {
        for (Year year : studentYears) {
            RadioButton rbYear = rbYearsMap.get(year.getType());
            rbYear.setText(year.getSubName());
        }
    }

    @Override
    public void refreshTitle(Year year) {
        btnTitle.setText(year.getSubName());
        RadioButton rbYear = rbYearsMap.get(year.getType());
        rbYear.setText(year.getSubName());
        rbYear.setChecked(true);
    }

    @Override
    public void refresh() {
        listAdapter.refresh();
    }

    @Override
    public void insertedNewCourse(Course course) {
        refresh();
    }

    private void showEditStudentDialog(Student student) {
        if (presenter.contentIsLoaded()) {
            AlertDialog alertDialog = new StudentEditorDialogBuilder(getActivity(), student, presenter).create();
            alertDialog.show();
            alertDialog.getWindow().setLayout(700, 600);
        }
    }

    private void showDeleteStudentConfirmationDialog(Student student) {
        AlertDialog alertDialog = new DeleteStudentConfirmationDialogBuilder(getActivity(), student, presenter).create();
        alertDialog.show();
        alertDialog.getWindow().setLayout(600, 400);
    }

    private void showCreateCourseDialog() {
        AlertDialog alertDialog = new CreatorNextCourseDialogBuilder(getActivity(), this).create();
        alertDialog.show();
        alertDialog.getWindow().setLayout(600, 400);
    }

    private void showNotFoundCourseDialog() {
        AlertDialog alertDialog = new NotFoundPreviousCourseDialogBuilder(getActivity()).create();
        alertDialog.show();
        alertDialog.getWindow().setLayout(600, 400);
    }

    private void showEditYearDialog() {
        if (presenter.contentIsLoaded()) {
            Year year = presenter.getDisplayYear();
            AlertDialog alertDialog = new YearEditorDialogBuilder(getActivity(), year, presenter).create();
            alertDialog.show();
            alertDialog.getWindow().setLayout(400, 600);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (databaseAdapter != null) {
            databaseAdapter.close();
        }
    }

}